<template>
  <div class="box">
    <div>
      <el-row :gutter="20">
        <el-col :span="20" class="box-contenter">
          <div class="grid-content bg-purple mrright">
            <el-button type="success" @click="addindex()">新增组</el-button>
          </div>
          <div
            class="grid-content bg-purple mrright"
            v-for="(item,index) in Permissionlist"
            :key="index"
          >
            <el-button type="success" class="buttonicon" @click="itemindex(item.id)">{{item.name}}</el-button>
            <i class="el-icon-circle-close hamburger-icon" @click="deletehandle()"></i>
          </div>
          <label for class="mrright table-wen">本组:</label>
          <div class="grid-content bg-purple mrright">
            <el-button type="info">Admin菜单权限</el-button>
          </div>
          <div class="grid-content bg-purple">
            <el-button type="success" @click="addxinzeng()">新增</el-button>
          </div>
        </el-col>
      </el-row>
    </div>
    <div class="box-table">
      <el-table :data="tableData" border style="width: 100%">
        <el-table-column prop="name" label="角色"></el-table-column>
        <el-table-column prop="coding" label="编码"></el-table-column>
        <!-- <el-table-column fixed="right" label="分配权限" width="400">
          <template>
            <el-button type="primary" size="small" @click="addgroup">新增</el-button>
            <el-button type="primary" size="small" @click="addgroup">删除</el-button>
            <el-button type="primary" size="small" @click="addgroup">查看</el-button>
          </template>
        </el-table-column>-->
        <el-table-column fixed="right" label="操作" width="400">
          <template slot-scope="{row}">
            <el-button type="primary" size="small" @click="addgroup(row)">菜单权限</el-button>
            <el-button type="primary" size="small" @click="addindexs(row,index)">编辑</el-button>
            <el-button type="primary" size="small" @click="treenode()">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 新增组-->
    <el-dialog :visible.sync="dialogFormVsisible">
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="usernames"
        label-position="left"
        label-width="70px"
        style="width: 400px; margin-left:50px;"
      >
        <el-form-item label="名称" prop="title">
          <el-input v-model="usernames.name" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVsisible = false">取消</el-button>
        <el-button type="primary" @click="handleCreate('dataFrom')">保存</el-button>
      </div>
    </el-dialog>
    <!-- 新增列表 -->
    <el-dialog :visible.sync="addFormVisible">
      <el-form
        ref="datafroms"
        :rules="rules"
        :model="temp"
        label-position="left"
        label-width="70px"
        style="width: 400px; margin-left:50px;"
      >
        <el-form-item label="名称" prop="title">
          <el-input v-model="temp.name" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addFormVisible = false">取消</el-button>
        <el-button type="primary" @click="updateData()">保存</el-button>
      </div>
    </el-dialog>
    <!-- 编辑 -->
    <el-dialog :visible.sync="dialogFormVisible">
      <el-form
        ref="datafroms"
        :rules="rules"
        :model="elint"
        label-position="left"
        label-width="70px"
        style="width: 400px; margin-left:50px;"
      >
        <el-form-item label="名称" prop="name">
          <el-input v-model="elint.name" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="elintbianji()">保存</el-button>
      </div>
    </el-dialog>
    <el-dialog :visible.sync="dialogTreeVisible1" width="35%">
      <elIndex
        ref="elIndex"
        :menudata="menus"
        :defaultProps="defaultProps"
        multiple
        nodeKey="id"
        :checkedKeys="defaultCheckedKeys"
      />
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogTreeVisible1 = false">取消</el-button>
        <el-button type="primary" @click="Setpermissions()">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { updateArticle } from "@/api/article";
import {
  roleList,
  groupList,
  deleteButton,
  groupAdd,
  groupDel,
  roleDel,
  setRoleAuth,
  Menumanagement,
  roleEdit
} from "@/api/user";

import elIndex from "@/components/el-index";
// const calendarTypeOptions = [
//   { key: 'CN', display_name: 'China' },
//   { key: 'US', display_name: 'USA' },
//   { key: 'JP', display_name: 'Japan' },
//   { key: 'EU', display_name: 'Eurozone' }
// ]
// const calendarTypeKeyValue = calendarTypeOptions.reduce((acc, cur) => {
//   acc[cur.key] = cur.display_name
//   return acc
// }, {})
export default {
  name: "home",
  components: {
    elIndex
  },
  data() {
    return {
      menus: [],
      elient: [],
      dialogTreeVisible1: false,
      addFormVisible: false,
      mus: [],
      role: "",
      usernames: {
        name: ""
      },
      elint: {
        id: "",
        name: ""
      },
      permissions: {
        role_id: "",
        auth_info: [],
        type: "1"
      },
      Deletepermissions: "",
      dialogFormVsisible: false,
      params: {
        group_id: ""
      },
      Permissionlist: [],
      defaultProps: {
        children: "childrenList",
        label: "menuName"
      },
      nodeKey: "menuId",
      defaultCheckedKeys: [],
      textMap: {
        update: "Edit",
        create: "Create"
      },
      dialogFormVisible: false,
      dialogTreeVisible: false,
      // calendarTypeOptions,
      temp: {
        name: "",
        group_id: ""
      },
      statusOptions: ["published", "draft", "deleted"],
      rules: {
        name: [{ required: true, message: "请输入名字", trigger: "blur" }]
      },
      dialogStatus: "",
      dialogStatuss: "",
      list: null,
      listLoading: true,
      tableData: []
    };
  },
  created() {
    this.defaultCheckedKeys = ["3"];
    // console.log(this.defaultCheckedKeys);
    this.userList();
    this.roleListdata();
    // this.roleListdata(element);
  },
  mounted() {
    this.defaultCheckedKeys = ["10"];
    // console.log(this.defaultCheckedKeys);
  },
  methods: {
    itemindex(group_id) {
      roleList({ group_id })
        .then(response => {
          this.tableData = response.data;
        })
        .catch(error => {
          console.log(error);
        });
    },
    handleClick() {},
    // 权限组列表
    userList() {
      groupList()
        .then(response => {
          this.Permissionlist = response.data;
          console.log(this.Permissionlist);
          response.data.forEach(element => {
            console.log(element);
            this.roleListdata(element);
          });
        })
        .catch(error => {
          console.log(error);
        });
    },
    // 新增组
    addindex(row, index) {
      // 新增组的编辑
      // 将数据赋值给新的空间
      this.dialogFormVsisible = true;
      // _index = index;
      // console.log(this.temp);
      // this.$nextTick(() => {
      //   this.$refs["dataForm"].clearValidate();
      // });
    },
    addindexs(row, index) {
      console.log(row);
      const indexss = row.name;
      this.dialogFormVisible = true;
      // Object.assign({}, row)
      this.elint.name = row.name;
      this.elint.id = row.id;
      console.log(this.elint);
    },
    handleCreate() {
      this.$refs["dataForm"].validate(valid => {
        if (valid) {
          groupAdd(this.usernames)
            .then(response => {
              console.log(response);
              // this.Permissionlist.splice(index, 1, this.usernames);
            })
            .then(() => {
              this.userList();
              this.$message({
                type: "success",
                message: "新增成功"
              });
              this.dialogFormVsisible = false;
            });
        }
      });
    },
    // 删除权限组
    deletehandle() {
      console.log(this.params.group_id);
      this.Deletepermissions = this.params.group_id;
      this.$confirm("是否确认要删除?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(async () => {
        await groupDel({ id: this.Deletepermissions });
        this.userList();
        this.$message({
          type: "success",
          message: "删除成功"
        });
      });
    },
    // 角色列表
    roleListdata(element) {
      console.log(element);
      this.params.group_id = element.id;
      roleList(this.params)
        .then(response => {
          response.data.forEach(elementa => {
            this.role = elementa.id;
            this.elient.name = elementa.name;
          });
          this.tableData = response.data;
        })
        .catch(error => {
          console.log(error);
        });
    },
    // 新增列表
    updateData() {
      debugger;
      this.temp.group_id = this.params.group_id;
      this.$refs["datafroms"].validate(valid => {
        if (valid) {
          updateArticle(this.temp).then(() => {
            this.$message({
              type: "success",
              message: "新增成功"
            });
            this.addFormVisible = true;
            this.roleListdata();
          });
        }
      });
    },
    // 删除角色列表
    treenode() {
      // console.log( this.params.group_id);
      //       this.Deletepermissions = this.params.group_id
      this.$confirm("是否确认要删除?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(async () => {
        await roleDel({ id: this.role });
        this.$message({
          type: "success",
          message: "删除成功"
        });
        this.roleListdata();
      });
    },
    edit() {
      console.log("res");
    },
    addgroup(element) {
      this.role = element.id;
      this.defaultProps = {
        label: "name",
        children: "children"
      };

      this.dialogTreeVisible1 = true;
      this.listdata();
    },
    getTree(tree) {
      return tree.map(({ children, ...item }) => ({
        ...item,
        label: item.name,
        children: children && children.length > 0 ? this.getTree(children) : []
      }));
    },
    listdata() {
      Menumanagement()
        .then(response => {
          this.menus = [
            {
              name: "test",
              label: "test",
              id: "test",
              auth_code: "102222",
              has_auth: 1,
              logo: "",
              parent_id: 0,
              sort: 2,
              type: 1,
              url: "/"
            },
            ...this.getTree(response.data)
          ];
          if (this.menus[0]) {
            var indexItem = this.$refs.elIndex;
            console.log(indexItem);
            this.mus = response.data.map(item => {
              this.permissions.auth_id;
              this.permissions.auth_info.push({ auth_id: item.id });
              console.log(this.permissions.auth_info);
            });
            const { label, children, nodeKey } = this.menus[0].label;
            this.defaultCheckedKeys = [nodeKey];
            // this.dialogTreeVisible = true; 
          }
          var tss = this.$refs.elIndex.$refs.tree.getCheckedKeys();
          tss.push(auth_info);
          console.log(tss);
        })
        .catch(error => {
          console.log(error);
          // reject(error)
        });
    },

    Setpermissions() {
      this.permissions.role_id = this.role;
      this.permissions.auth_info = JSON.stringify(this.permissions.auth_info);
      setRoleAuth(this.permissions).then(response => {
        this.$message({
          type: "success",
          message: "新增成功"
        });
        this.dialogTreeVisible1 = false;
        this.listdata();
      });
    },
    addxinzeng() {
      this.addFormVisible = true;
    },
    // 编辑角色列表
    elintbianji() {
      this.elient.id = this.role;
      roleEdit(this.elint).then(response => {
        // elient.push()
        console.log(response);
        this.$message({
          type: "success",
          message: "编辑成功"
        });
        this.dialogFormVisible = false;
        this.roleListdata();
        console.log(this.roleListdata());
      });
    }
  }
};
</script>
<style lang="scss" scoped>
.box {
  margin: 20px 20px 20px 20px;
  height: 100%;
  width: 100%;
  .box-table {
    padding-top: 12px;
  }
  .table-wen {
    font-size: 15px;
    color: #6f6f6f;
  }
}
.box-contenter {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  .mrright {
    position: relative;
    padding-right: 20px;
  }
  .mrright:hover .hamburger-icon {
    display: block;
  }
  // .buttonicon{
  // }
  .hamburger-icon {
    display: none;
    position: absolute;
    top: 12px;
    right: 22px;
  }
}
</style>
